﻿using System.IO;
using System.Security.Cryptography;

namespace Basic
{
    /// <summary>
    /// 加密相关的辅助类
    /// </summary>
    public static class Encrypt
    {
        /// <summary>
        /// 计算字节流的MD5
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string MD5(byte[] content)
        {
            return MD5(content, 0, content.Length - 1);
        }

        /// <summary>
        /// 计算字节流的MD5
        /// </summary>
        /// <param name="content"></param>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        /// <param name="format">x2: 为32位; x3: 结果为48位; x4: 结果为64位</param>
        /// <returns></returns>
        public static string MD5(byte[] content, int startIndex, int endIndex, string format = "x2")
        {
            var md5 = System.Security.Cryptography.MD5.Create();
            byte[] result = md5.ComputeHash(content, startIndex, endIndex);

            var sb = TempStringBuilderCache.Acquire();
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString(format));
            }
            return TempStringBuilderCache.GetStringAndRelease(sb).ToLower();
        }

        /// <summary>
        /// 计算可读写目录下的文件的MD5
        /// </summary>
        /// <param name="writablePathFile">文件完整路径</param>
        /// <returns></returns>
        public static string MD5(string writablePathFile)
        {
            if (!File.Exists(writablePathFile))
            {
                return string.Empty;
            }

            using (FileStream file = new FileStream(writablePathFile, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                byte[] hash_byte = md5.ComputeHash(file);
                string str = System.BitConverter.ToString(hash_byte);
                str = str.Replace("-", "");
                return str.ToLower();
            }
        }
    }
}
